package com.yvon.core;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yvon.core.pojo.TreeEntity;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * @author : Yvon
 * @since : 2021-06-29
 */
public class BaseTreeServiceImpl<T extends TreeEntity, M extends BaseMapper<T>> extends BaseServiceImpl<T, M> implements BaseTreeService<T> {
    public BaseTreeServiceImpl() {
    }


    @Override
    public T getChildrenById(Serializable id) {
        T t = getById(id);
        getChildrenNode(t);
        return t;
    }


    public void getChildrenNode(T t) {
        if (Objects.nonNull(t)) {
            while (StrUtil.isNotBlank(t.getParentId())) {

                List<T> node = getByParentId(t.getParentId());
                if (CollUtil.isNotEmpty(node)) {
                    t.setChildren(node);
                    node.forEach(this::getChildrenNode);

                }
            }
        }
    }

    public List<T> getByParentId(Serializable parentId) {
        QueryWrapper<T> qw = new QueryWrapper<>();
        qw.eq("parent_id", parentId);
        return list(qw);
    }


    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        if (CollUtil.isNotEmpty(idList)) {
            idList.forEach(this::removeById);
        }
        return true;
    }


    @Override
    public boolean removeById(Serializable id) {
        super.removeById(id);
        List<T> children = getByParentId(id);
        if (CollUtil.isNotEmpty(children)) {
            children.forEach((child) -> this.removeById(child.getId()));
        }
        return true;
    }



}
